package com.right.health.app.ui.registered;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.magic.basic.utils.TimeUtil;
import com.magic.basic.utils.ToastUtil;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.app.App;
import com.right.health.app.base.BasePresenterActivity;
import com.right.health.app.bean.AppUserResponse;
import com.right.health.app.bean.DepartmentInfo;
import com.right.health.app.bean.DoctorResponse;
import com.right.health.app.bean.DoctorScheduleResponse;
import com.right.health.app.bean.FamilyResponse;
import com.right.health.app.bean.PayInfo;
import com.right.health.app.bean.VisitCardResponse;
import com.right.health.app.constants.AppConfig;
import com.right.health.app.constants.BroadCastKey;
import com.right.health.app.net.OrderApi;
import com.right.health.app.net.UserApi;
import com.right.health.app.ui.me.FamilyActivity;
import com.right.health.app.ui.me.MeReserveActivity;
import com.right.health.app.ui.me.MeVisitCardActivity;
import com.right.health.app.utils.WeekUtils;
import com.vendor.social.PayApi;
import com.vendor.social.model.PayType;
import com.vendor.social.pay.WxPay;

import java.text.DecimalFormat;

/*
 * Created by hopeliao on 2019-09-26
 *
 */
public class RegisteredConfirmActivity extends BasePresenterActivity implements View.OnClickListener , OnHttpListener, PayApi.OnPayListener {
    private static final int PAY_TYPE_WX = 10;
    private static final int PAY_TYPE_ALIPAY = 11;

    private static final int HTTP_CODE_GET_USER_INFO = 1;

    private static final String EXTRA_DEPARTMENT = "extra:DepartmentInfo";
    private static final String EXTRA_DOCTOR = "extra:doctor";
    private static final String EXTRA_SCHEDULE = "extra:Schedule";

    private static final int REQUEST_CODE_FAMILY = 1;
    private static final int REQUEST_CODE_CARD = 2;

    private View[] mPayItems;
    private ImageView[] mPaySelectedImage;

    private DepartmentInfo mDepaInfo;
    private DoctorResponse.DoctorInfo mDoctorInfo;
    private DoctorScheduleResponse.DoctorScheduleInfo mScheduleInfo;

    private TextView mDoctorNameTv, mDepartmentNameTv, mTreatTimeTv, mMoneyTv;

    private FamilyResponse.FamilyInfo mFamilyInfo;

    private TextView mPatientNameTv, mCardNumberTv;

    private String mMemberId;

    private OrderApi mOrderApi;

    private int mOrderType;

    private UserApi mUserApi;

    private boolean mIsVertificationSucc;

    @Override
    public void onCreate(Bundle bundle, String s) {
        setContentView(R.layout.registered_confirm);
    }

    @Override
    public void findView() {
        mCardNumberTv = (TextView) findViewById(R.id.tv_card_number);
        mPatientNameTv = (TextView) findViewById(R.id.tv_patient_name);
        mMoneyTv = (TextView) findViewById(R.id.tv_money);
        mTreatTimeTv = (TextView) findViewById(R.id.tv_treat_time);
        mDepartmentNameTv = (TextView) findViewById(R.id.tv_department);
        mDoctorNameTv = (TextView) findViewById(R.id.tv_doctor_name);

        mPayItems = new View[3];
        mPaySelectedImage = new ImageView[3];
        mPayItems[0] = findViewById(R.id.rl_pay_alipay_item);
        mPayItems[1] = findViewById(R.id.rl_pay_wechat_item);
        mPayItems[0].setVisibility(View.GONE);
        mPayItems[2] = findViewById(R.id.rl_pay_social_security_item);
        for (View mPayItem : mPayItems) {
            mPayItem.setOnClickListener(this);
        }
        mPaySelectedImage[0] =  findViewById(R.id.iv_selected_alipay);
        mPaySelectedImage[1] =  findViewById(R.id.iv_selected_wechat);

        findViewById(R.id.tv_switch_member).setOnClickListener(this);
        findViewById(R.id.tv_linked_card).setOnClickListener(this);
        findViewById(R.id.btn_sure).setOnClickListener(this);


        mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), ""));
    }

    @Override
    public void initialize() {
        mOrderApi = new OrderApi();
        mOrderApi.setListener(this);

        mUserApi = new UserApi();
        mUserApi.setListener(this);

        mUserApi.addRequestCode(HTTP_CODE_GET_USER_INFO);
        mUserApi.getUserInfo();

        refreshUIByUser(App.getInstance().getUser());

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mDepaInfo = bundle.getParcelable(EXTRA_DEPARTMENT);
            mDoctorInfo = bundle.getParcelable(EXTRA_DOCTOR);
            mScheduleInfo = bundle.getParcelable(EXTRA_SCHEDULE);

            refreshUI();
        }
    }

    public static void applyActivity(Activity act, DepartmentInfo depaInfo, DoctorResponse.DoctorInfo doctor, DoctorScheduleResponse.DoctorScheduleInfo scheduleInfo) {
        Intent intent = new Intent(act, RegisteredConfirmActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_DEPARTMENT, depaInfo);
        bundle.putParcelable(EXTRA_DOCTOR, doctor);
        bundle.putParcelable(EXTRA_SCHEDULE, scheduleInfo);
        intent.putExtras(bundle);

        act.startActivity(intent);
    }

    private void refreshUIByUser(AppUserResponse.AppUserInfo userInfo) {
        mMemberId = userInfo.memberid;
        mPatientNameTv.setText("本人");
        if(!TextUtils.isEmpty(userInfo.patientidcardnum) ) {
            mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), userInfo.patientidcardnum));
            findViewById(R.id.tv_linked_card).setVisibility(View.GONE);
        } else {
            mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), ""));
            findViewById(R.id.tv_linked_card).setVisibility(View.VISIBLE);
              }

        mIsVertificationSucc = userInfo.isVertificationSucc();
    }

    private void refreshUI() {
        mDoctorNameTv.setText(mDoctorInfo.doctorname);
        mDepartmentNameTv.setText(mDepaInfo.deptname);

        String format = "%s（%s） %s";
        String regdate = TimeUtil.convertTime(AppConfig.FORMAT_TIME, mScheduleInfo.regdate);
        String week = WeekUtils.getWeekOfDate(mScheduleInfo.regdate);
        mTreatTimeTv.setText(String.format(format, regdate, week, mScheduleInfo.shiftname));

        float money = Float.parseFloat(mScheduleInfo.regfee) + Float.parseFloat(mScheduleInfo.treatfee);
/*        DecimalFormat decimalFormat = new DecimalFormat("###,###.0");
        String moneyValue = decimalFormat.format(money);
        mMoneyTv.setText(moneyValue+"元");*/
        mMoneyTv.setText(money + "元");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_FAMILY) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    mFamilyInfo = bundle.getParcelable(BroadCastKey.DATA);
                    if (mFamilyInfo != null) {
                        mMemberId = mFamilyInfo.memberid;
                        mPatientNameTv.setText(mFamilyInfo.membername);
                        if (TextUtils.isEmpty(mFamilyInfo.patientidcardnum)) {
                            findViewById(R.id.tv_linked_card).setVisibility(View.VISIBLE);
                            mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), ""));

                        }else {
                            findViewById(R.id.tv_linked_card).setVisibility(View.GONE);
                            mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), mFamilyInfo.patientidcardnum));
                        }

                    }
                }
            } else if (requestCode == REQUEST_CODE_CARD) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    VisitCardResponse.VisitCardInfo info = bundle.getParcelable(BroadCastKey.DATA);
                    if (info != null) {
                        mCardNumberTv.setText(String.format(getResources().getString(R.string.format_card_number), info.patientidcardnum));
                        findViewById(R.id.tv_linked_card).setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_pay_alipay_item:
            case R.id.rl_pay_wechat_item:
            case R.id.rl_pay_social_security_item:
                if(v.getId() == R.id.rl_pay_wechat_item) {
                    mOrderType = PAY_TYPE_WX;
                } else if(v.getId() == R.id.rl_pay_alipay_item) {
                    mOrderType = PAY_TYPE_ALIPAY;
                }
                for (int i = 0; i < mPayItems.length; i++) {
                    if (mPayItems[i] == v) {
                        mPayItems[i].setSelected(true);
                        if (mPaySelectedImage[i] != null) {
                            mPaySelectedImage[i].setVisibility(View.VISIBLE);
                        }

                    } else {
                        mPayItems[i].setSelected(false);
                        if (mPaySelectedImage[i] != null) {
                            mPaySelectedImage[i].setVisibility(View.INVISIBLE);
                        }
                    }
                }
                break;
            case R.id.tv_switch_member: //添加就诊人
                FamilyActivity.makeActivity(this, true, false, REQUEST_CODE_FAMILY);
                break;
            case R.id.tv_linked_card://关联就诊卡
                if (!TextUtils.isEmpty(mMemberId)) {
                    MeVisitCardActivity.applyActivity(this, mMemberId, true, REQUEST_CODE_CARD);
                }
                break;
            case R.id.btn_sure://确定
                send2Net();
                break;
        }
    }

    private void send2Net() {
        if(!mIsVertificationSucc) {
            ToastUtil.show(this, "请先实名认证");
            return;
        }
        if (mDepaInfo == null) {
            ToastUtil.show(this, "请选择就诊科室");
            return;
        }
        if(mDoctorInfo == null) {
            ToastUtil.show(this, "请选择就诊医生");
            return;
        }
        if(mScheduleInfo == null) {
            ToastUtil.show(this, "请选择就诊时间");
            return;
        }
        if(mOrderType == 0) {
            ToastUtil.show(this, "请选择支付方式");
            return;
        }

        mOrderApi.setTag(mOrderType);
        mOrderApi.addOrder(App.getInstance().getUserId(), mMemberId, mScheduleInfo.scheduleid, mOrderType);

//        WxPay wxPay = new WxPay(this);
//        wxPay.setOnPayListener(this);
//        wxPay.setOutTradeNo("a12345");
//        wxPay.setNotifyUrl("https://www.baidu.com");
//        wxPay.pay(getString(R.string.app_name), "支付", String.valueOf(1));
    }

    @Override
    public void onResponse(Request request, Response response) {
        if(response.isResponseFail()) {
            ToastUtil.show(this, response.error);
        } else {
            if (response.targetData instanceof AppUserResponse) {
                AppUserResponse appUserResponse = response.cast(AppUserResponse.class);
                App.getInstance().refreshUser(appUserResponse.user);

                refreshUIByUser(appUserResponse.user);
            } else if(response.targetData instanceof PayInfo) {
                PayInfo payInfo = response.cast(PayInfo.class);
                int payType = Integer.valueOf(String.valueOf(request.tag));

                if(payType == PAY_TYPE_ALIPAY) {
                    PayApi.pay(this, PayType.ALIPAY, payInfo.orderstr, this);
                } else if(payType == PAY_TYPE_WX) {
                    WxPay wxPay = new WxPay(this);
                    wxPay.setOnPayListener(this);
                    wxPay.pay(payInfo.wxdata);
                }

            }
        }
    }

    @Override
    public void onPayOk() {
        startIntent(MeReserveActivity.class);
    }

    @Override
    public void onPayFail(String msg) {
        ToastUtil.show(this, "支付失败");
        startIntent(MeReserveActivity.class);
    }
}
